package oj;

import java.util.Arrays;

/**
 * @author 郝文雪
 * @date 2022/9/1 10:53
 * @Description Test
 */
public class LC16 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int n=nums.length;
        int min=10000000;
        for(int i=0;i<n;i++){
            if(i>0 && nums[i]==nums[i-1]){
                continue;
            }
            int j=i+1;
            int k=n-1;
            while(j<k){
                int sum=nums[i]+nums[j]+nums[k];
                if(sum==target){
                    return sum;
                }
                if(Math.abs(sum-target)<Math.abs(min-target)){
                    min=sum;
                }
                if(sum>target){
                    int k0=k-1;
                    while(j<k0 && nums[k]==nums[k0]){
                        k0--;
                    }
                    k=k0;
                }else{
                    int j0=j+1;
                    while(j0<k && nums[j]==nums[j0]){
                        j0++;
                    }
                    j=j0;
                }
            }

        }
        return min;
    }
}
